package com.example.thirdhomework

import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.thirdhomework.databinding.ActivityMainBinding
import java.io.Serializable

const val KEY1="key1"
data class Person(val name:String,val age:Int) :Serializable
data class Student(val name:String,val age:Int,val teacher:Person):Serializable
class MainActivity : AppCompatActivity() {
    //lateint是延迟初始化
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)//绑定布局，其中的按钮什么的就不需要用id去找了
        setContentView(binding.root)//设置布局
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        binding.button.setOnClickListener{
            val intent=Intent(this,FirstActivity::class.java)
            val student=Student(binding.editTextText.text.toString(),20,Person("zhangsan",30))
            intent.putExtra(KEY1,student)
            startActivity(intent)
        }
        val  launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                binding.textView2.text = data?.getStringExtra("KEY1")
            }
        }

        binding.buttonsecond.setOnClickListener{
            val intent =Intent(this,SecondActivity::class.java)
            startActivityForResult(intent,0)

        }



        val launcher2=registerForActivityResult(ActivityResultContracts.TakePicturePreview()){
            binding.imageView.setImageBitmap(it)
        }
        binding.buttonthird.setOnClickListener{
            launcher2.launch(null)
        }

        binding.button3.setOnClickListener{
            val intent=Intent(this,ThirdActivity::class.java)
            startActivity(intent)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==0){
            if(resultCode==1){
                binding.textView2.text=data?.getStringExtra("KEY1")
            }
        }
    }
}